package DataBase;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Logger;

import com.mysql.jdbc.log.Log;

import DataObjects.OrderSearch;

public class GetOrders {
	private OrderSearch search;
	private Vector<Vector> orders;

	public GetOrders(OrderSearch srch) {
		this.search = srch;
		this.orders = new Vector<Vector>();
	}

	public Vector<Vector> get() {
		SQLConnection sc = new SQLConnection();

		try {
			String sql = "SELECT "
					+ "orders.`order_id`, "
					+ "supplier.suppName, "
					+ "orders.`date`, "
					+ "orders.`time`, "
					+ "orders.`status`, "
					+ "item.Iname "
					+ "FROM orders, items_in_order, item, supplier "
					+ "WHERE item.Iid = items_in_order.item_id "
					+ "AND orders.order_id = items_in_order.order_id "
					+ "AND orders.supplier_id = supplier.suppID "
					+ " AND item.Iname LIKE '%%' "
					+ " AND supplier.suppName LIKE '%%' "
					+ " AND orders.date >= DATE('1970-1-1') "
					+ "AND orders.time >= TIME('00:00:00') "
					+ " ORDER BY orders.order_id DESC, orders.date DESC, orders.time DESC "
					+ " LIMIT 100 ";
			PreparedStatement ps = sc.getConnection().prepareStatement(sql);
			// ps.setString(1,"'%" + this.search.itemName + "%'");
			// ps.setString(2, "'%" + this.search.supplierName + "%'");
			// ps.setString(3, this.search.dateStart.toString());
			// ps.setString(4, this.search.timeStart.toString());
			// ps.setInt(5, this.search.limit);

			

			ResultSet rs = ps.executeQuery();

			ResultSetMetaData rsmd = rs.getMetaData();

			while (rs.next()) {

				Vector<String> row = new Vector<String>();
				for (int col = 1; col <= rsmd.getColumnCount(); col++) {
					row.add(rs.getString(col));
				}// for

				boolean flag = false;
				for (int i = 0; i < orders.size(); i++) {
					flag = false;
					if (orders.get(i).get(0).equals(row.get(0))) {
						orders.get(i).set(5, orders.get(i).get(5) + "\n" + row.get(5));
						flag = true;
						i = orders.size();
					}
				}
				if (flag == false)
					orders.add(row);
			}// while
			ps.close();
			rs.close();
			sc.getConnection().close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return this.orders;
	}
}
